package com.socket.service;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * socket服务类
 *
 * @author ww
 * @date 2018/7/6
 */
@Component
@ServerEndpoint(value = "/webSocket/{user}")
public class WebSocketService {
    /**静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。*/
    private static CopyOnWriteArraySet<WebSocketService> webSocketSet = new CopyOnWriteArraySet<WebSocketService>();

    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/
    private Session session;

    /**接收user*/
    private String user="";
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session, @PathParam("user") String user) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        this.session = session;
        //test
//        this.user = session.getId();
        this.user = user;
        //加入set中
        webSocketSet.add(this);
        addOnlineCount();           //在线数加1
        System.out.println(format.format(new Date())+"【" + this.user + "】连接上服务器===当前在线人数【" + getOnlineCount() + "】");
        try {
            sendMessage(format.format(new Date()) + " 连接成功");
        } catch (IOException e) {
            System.out.println("webSocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //从set中删除
        webSocketSet.remove(this);
        //在线数减1
        subOnlineCount();
        System.out.println(format.format(new Date())+"【" + this.user + "】退出了连接==当前在线人数【" + getOnlineCount() + "】");
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     **/
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("【" + this.user + "】客户端的发送消息:【" + message + "】");
        //群发消息
        String msgTo = "【" + this.user + "】发送消息:\n【" + message + "】";
        String msgMe = "【我】发送的消息:\n" + message;
        for (WebSocketService item : webSocketSet) {
//            if ( item.session.isOpen() ){}
            if (this.user.equals(item.user)) {
                item.sendMessage(msgMe);
            }else {
                item.sendMessage(msgTo);
            }
        }
    }

    /**
     * 判断socket的session是否连接正常
     * @param session 当前会话session
     * @return true/false
     */
    public Boolean socketOpen(Session session){
        return session.isOpen();
    }

    /**
     * @param session session会话
     * @param error 异常
     */
    @OnError
    public void onError(Session session, Throwable error) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        System.out.println(format.format(new Date())+"发生错误");
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     **/
    public static Boolean sendInfo(String message, @PathParam("user") String user) throws IOException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(new Date()) + " 推送消息给"+ (user == null ? "大家" : user) +"，推送内容:"+message);
        int sentResult = 0;
        for (WebSocketService item : webSocketSet) {
            //这里可以设定只推送给这个user的，为null则全部推送
            if(user==null) {
                sentResult = 1;
                item.sendMessage(message);
            }else if(item.user.equals(user)){
                //判断当前会话socket是否正常连接，
                if (item.session.isOpen()){
                    sentResult = 1;
                    item.sendMessage(message);
                    break;
                }else {
                    return false;
                }
            }
        }
        return sentResult != 0;
    }

    private static synchronized int getOnlineCount() {
        return onlineCount;
    }

    private static synchronized void addOnlineCount() {
        WebSocketService.onlineCount++;
    }

    private static synchronized void subOnlineCount() {
        WebSocketService.onlineCount--;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        WebSocketService that = (WebSocketService) o;
        return Objects.equals(session, that.session) &&
                Objects.equals(user, that.user);
    }

    @Override
    public int hashCode() {
        return Objects.hash(session, user);
    }
}
